import store from '@/store'
import Cart from '@/views/layout/Cart.vue'
import Category from '@/views/layout/Category.vue'
import Home from '@/views/layout/Home.vue'
import Layout from '@/views/layout/Layout.vue'
import User from '@/views/layout/User.vue'
import Login from '@/views/login/Login.vue'
import Search from '@/views/search/index.vue'
import SearchList from '@/views/search/list.vue'
import ProDetail from '@/views/prodetail/index.vue'
import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [{
        path: '/home',
        component: Home,
      },
      {
        path: '/category',
        component: Category
      },
      {
        path: '/cart',
        component: Cart
      },
      {
        path: '/user',
        component: User
      }
    ]
  },
  {
    path:'/search',
    component:Search
  },
  {
    path:'/searchList',
    component:SearchList
  },
  {
    path:'/prodetail/:id',
    component:ProDetail
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const authUrl = ['/pay', '/myOrder']

router.beforeEach((to, from, next) => {
  // 1. to   往哪里去， 到哪去的路由信息对象  
  // 2. from 从哪里来， 从哪来的路由信息对象
  // 3. next() 是否放行
  //    如果next()调用，就是放行
  //    next(路径) 拦截到某个路径页面
  const token = store.getters.token
  // 如果不是在需要校验的url中则放行
  if (!authUrl.includes(to.path)) {
    next()
    return
  }
  // 没有用户token需要登录，有则放行
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
